import i18n from '@/i18n'
// const DEFAULT_BASE_URL = 'https://h5ehos.sznxai.com' //'http://nv38644510d.vicp.fun' // 替换为你的后端接口地址
// const DEFAULT_BASE_URL = 'https://h5ehos.sznxai.com' // "https://tcmai.one"  // http://192.168.1.160:8000

const DEFAULT_BASE_URL = 'http://192.168.1.160:8000'

// request.js

// 获取token的函数
function getToken() {
  const userString = uni.getStorageSync('user')

  if (userString) {
    try {
      const userObject = JSON.parse(userString)
      return userObject && userObject.token ? userObject.token : ''
    } catch (e) {
      // 如果解析失败（比如存储的不是一个有效的JSON），打印错误并返回空
      console.error('解析 storage 中的 "user" 失败:', e)
      return ''
    }
  }

  return ''
}

// 获取当前语言设置的函数
function getLanguage() {
  // 从本地存储中读取用户设置的语言
  const lang = uni.getStorageSync('userLanguage')
  // 如果没有设置，可以提供一个默认值，例如 'zh' (中文)
  return lang || 'zh'
}

// 全局loading计数器，防止多请求时提前关闭
let loadingCount = 0
function showLoading(title) {
  // 如果没传title，用国际化
  if (!title) {
    title = i18n.global.t('common.loading')
  }
  if (loadingCount === 0) {
    uni.showLoading({ title, mask: true })
  }
  loadingCount++
}
function hideLoading() {
  loadingCount = Math.max(loadingCount - 1, 0)
  if (loadingCount === 0) {
    uni.hideLoading()
  }
}

// 全局错误处理
function handleError(res, customError) {
  if (!customError) {
    uni.showToast({ title: res.message || '请求失败', icon: 'none' })
  }
}

// 通用请求
function request({
  url,
  method = 'GET',
  data = {},
  header = {},
  showLoading: needLoading = true,
  loadingText,
  baseURL = DEFAULT_BASE_URL,
  customError = false // 是否自定义错误处理
}) {
  // 请求拦截
  const token = getToken()
  const userLanguage = uni.getStorageSync('userLanguage') || 'zh'
  const realHeader = {
    'Content-Type': 'application/json',
    'Accept-Language': userLanguage,
    ...header
  }
  if (token) {
    realHeader['Authorization'] = token
  }

  if (needLoading) showLoading(loadingText)

  return new Promise((resolve, reject) => {
    uni.request({
      url: baseURL + url,
      method,
      data,
      header: realHeader,
      timeout: 30000, // 30秒超时
      success: res => {
        if (needLoading) hideLoading()

        // 响应拦截
        if (res.statusCode === 200) {
          // 业务成功
          if (res.data && (res.data.code === 0 || res.data.success)) {
            resolve(res.data)
          } else {
            // 业务失败
            handleError(res.data, customError)
            reject(res.data)
          }
        } else if (res.statusCode === 401) {
          // 未授权，自动跳转登录
          uni.removeStorageSync('token')
          uni.showToast({ title: '请重新登录', icon: 'none' })
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/login/index' })
          }, 100)
          reject(res.data)
        } else {
          handleError(res.data, customError)
          reject(res.data)
        }
      },
      fail: err => {
        if (needLoading) hideLoading()
        if (!customError) {
          uni.showToast({ title: '网络错误', icon: 'none' })
        }
        reject(err)
      }
    })
  })
}

// 文件上传
function upload({
  url,
  filePath,
  name = 'file',
  formData = {},
  header = {},
  showLoading: needLoading = true,
  loadingText,
  baseURL = DEFAULT_BASE_URL,
  customError = false
}) {
  const token = getToken()
  const language = getLanguage()
  const realHeader = {
    'Accept-Language': language,
    ...header
  }
  if (token) {
    realHeader['Authorization'] = token
  }
  if (needLoading) showLoading(loadingText)

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseURL + url,
      filePath,
      name,
      formData,
      header: realHeader,
      timeout: 60000, // 60秒超时，文件上传需要更长时间
      success: res => {
        if (needLoading) hideLoading()
        let data = res.data
        try {
          data = JSON.parse(res.data)
        } catch (e) {}
        if (res.statusCode === 200 && (data.code === 0 || data.success)) {
          resolve(data)
        } else {
          handleError(data, customError)
          reject(data)
        }
      },
      fail: err => {
        if (needLoading) hideLoading()
        if (!customError) {
          uni.showToast({ title: '上传失败', icon: 'none' })
        }
        reject(err)
      }
    })
  })
}

// 快捷方法
function get(url, data = {}, options = {}) {
  return request({ url, method: 'GET', data, ...options })
}
function post(url, data = {}, options = {}) {
  return request({ url, method: 'POST', data, ...options })
}
function put(url, data = {}, options = {}) {
  return request({ url, method: 'PUT', data, ...options })
}
function del(url, data = {}, options = {}) {
  return request({ url, method: 'DELETE', data, ...options })
}

export { request, get, post, put, del, upload, DEFAULT_BASE_URL, getToken }
